home *** CD-ROM | disk | FTP | other *** search
- Path: senior.nectec.or.th!nwg!finn
- From: finn@nwg.nectec.or.th (James Finn)
- Newsgroups: comp.lang.c++
- Subject: Re: Friends....
- Date: 3 Jan 1996 08:59:28 GMT
- Organization: National Electronics and Computer Technology Center, Bangkok
- Message-ID: <4cdghg$1ep@senior.nectec.or.th>
- References: <4c9srh$g2l@ixnews3.ix.netcom.com>
- NNTP-Posting-Host: nwg.nectec.or.th
- X-Newsreader: TIN [version 1.2 PL2]
-
- Chris Morris (cpmorris@popd.ix.netcom.com) wrote:
- : I am a beginner with C++ and have a question concerning the
- : declaration of 'friend' functions.
-
- Question about why operator << is declared a friend instead of
- a member.
-
- There is no other way to do it. Here is the problem.
- When an operator is defined as a member, the left
- operand must be a variable of the class type. In
- the case of
-
- cout << variable
-
- the left operand is an ostream.
-
- Say you have a class CL, with variables:
-
- CL cl1, cl2.
-
- When you write
-
- cl1 + cl2
-
- if operator + is defined as a member function, this compiles
- as
- cl1.operator +(cl2)
-
- If it's defined as a friend, it compiles as
-
- operator +(cl1, cl2)
-
- Similarly, the only way << could be a member function
- is if it were a member function for the ostream class,
- since the left operand is the ostream. Since you
- can't (or don't want to) go mess with the source
- for the iostream library, you must define << as
- a friend function.
-
- : This is the confusing part. How can the << and >> be used in the
- : definitions of << and >>?
-
- Well, it's an overloaded function. The types being used in
- the function definition are not the same as the type for
- which the function is being defined. For example, if I
- were writing a << function to read complex numbers, I
- could use the fact that << is already defined to write
- real numbers. The complex << would write two doubles,
- using << to write them.
-
- : Is seems like the new << and >> friend
- : functions are just defining their own implementations for handling the
- : user-defined type. This is overloading, isn't it?
-
- Exactly.
-
- --James
-